package org.duomn.ichat.gui.compose;

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.duomn.ichat.entity.FontAttribute;

public class FontPane extends JPanel {
	private static final long serialVersionUID = 8535045941871531696L;
	private FontAttribute fontSet;
	
	public FontPane() {
		this.fontSet = new FontAttribute();
		this.setLayout(new FlowLayout(FlowLayout.LEADING, 2, 1));
		final JComboBox nameCbx = new JComboBox(new String[]{"宋体", "黑体", "Dialog", "Gulim"});
		fontSet.setFontName("宋体");
		nameCbx.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				fontSet.setFontName((String) nameCbx.getSelectedItem());
				fireFontChangeListener();
			}
		});
		final JComboBox sizeCbx = new JComboBox(new Integer[] {12, 14, 18, 22, 30, 40});
		fontSet.setFontSize(12);
		sizeCbx.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				fontSet.setFontSize((Integer) sizeCbx.getSelectedItem());
				fireFontChangeListener();
			}
			
		});
		final JToggleButton boldTgl = new JToggleButton("粗体"); // TODO 图标
		fontSet.setBold(false);
		boldTgl.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				fontSet.setBold(boldTgl.isSelected());
				fireFontChangeListener();
			}
		});
		final JToggleButton italicTgl = new JToggleButton("斜体"); 
		fontSet.setItalic(false);
		italicTgl.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				fontSet.setItalic(italicTgl.isSelected());
				fireFontChangeListener();
			}
		});
		final JToggleButton underTgl = new JToggleButton("下划线");
		fontSet.setUnderline(false);
		underTgl.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				fontSet.setUnderline(underTgl.isSelected());
				fireFontChangeListener();
			}
		});
//		JColorChooser 
		add(nameCbx);
		add(sizeCbx);
		add(boldTgl);
		add(italicTgl);
		add(underTgl);
	}
	
	public FontAttribute getFontAttr() {
		return this.fontSet;
	}
	
	private void fireFontChangeListener() {
		for (FontChangeListener fcl : fontListens) {
			fcl.fontChange(fontSet);
		}
	}
	
	private List<FontChangeListener> fontListens = new ArrayList<FontChangeListener>();
	
	public void addFontChangeListener(FontChangeListener fcl) {
		this.fontListens.add(fcl);
	}
	
	public void removeFontChangeListener(FontChangeListener fcl) {
		this.fontListens.remove(fcl);
	}
	
	public static interface FontChangeListener {
		public void fontChange(FontAttribute fontAttr);
	}

}
